﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ZhimeiSoft.Framework.Common.Enums;
using ZhimeiSoft.Framework.Client.Utils;
using ZhimeiSoft.CharmManager.DOL;
using ZhimeiSoft.CharmManager.Client.Manager;
using ZhimeiSoft.Framework.Common.MathUtils;
using ZhimeiSoft.Framework.Client.Base;

namespace ZhimeiSoft.CharmManager.Client.Forms
{
    public partial class frmCustomerServiceItemAdd : FormBase
    {
        #region 字段
        private int _customerid = -1;
        private int _serviceitemid = -1;
        private ControlClassModeEnum _mode;
        private DBEntityCustomerServiceItem _customerserviceitem;
        #endregion

        #region 属性
        public ControlClassModeEnum Mode
        {
            get { return _mode; }
            set { _mode = value; }
        }

        public int CustomerID
        {
            set { _customerid = value; }
        }
        #endregion


        public frmCustomerServiceItemAdd()
        {
            InitializeComponent();

            serviceItemSearch1.onSearchKeyWordChanged = this.SearchServiceItem;
        }

        public frmCustomerServiceItemAdd(DBEntityCustomerServiceItem customerserviceitem) : this()
        {
            this._customerserviceitem = customerserviceitem;
        }

        private void SearchServiceItem(string sKeyword)
        {
            DataSet ds = new DataSet();
            string error = string.Empty;
            string sFilter = string.Format("{0}='{1}'", DBEntityServiceItem.FieldName.STATE, DBEntityServiceItem.ENUM_STATE.C0A);
            bool bFlag = BussinessProxyManager.Instance.QueryServiceItem(sFilter, out ds, out error);
            if (bFlag == false)
            {
                MsgBox.MsgInfo("获取服务信息失败\r\n" + error);
                return;
            }

            DataTable dtResult = SearchServiceItemInfo(ds, sKeyword);
            DataSet dsResult = new DataSet();
            dsResult.Tables.Add(dtResult);

            frmServiceItemList form = new frmServiceItemList(dsResult);
            if (form.ShowDialog() == DialogResult.OK)
            {
                DataRow dr = form.SelectedRow;
                DBEntityServiceItem item = new DBEntityServiceItem(dr);
                _serviceitemid = item.SERVICEITEMID;
                lblItemName.Text = item.SNAME;
                lblCode.Text = item.SERVICEITEMCODE;
                lblPrice.Text = item.SPRICE.ToString();
                lblTimeSpan.Text = item.STIMESPAN.ToString();
                iiServiceCount.Value = item.SCOUNT;

                if (item.SAVAILABLEDAYS == -1)
                    dtiEndTime.Value = Convert.ToDateTime("3000-12-31");
                else
                    dtiEndTime.Value = dtiBuyTime.Value.AddDays(item.SAVAILABLEDAYS);

                if (Mode == ControlClassModeEnum.emInsert)
                {
                    iiRemainServiceCount.Value = iiServiceCount.Value;
                    txtMoney.Text = "0";
                }

            }
        }

        /// <summary>
        /// 根据字符串进行全文搜索
        /// </summary>
        /// <param name="dsServiceItem"></param>
        /// <param name="serchStr"></param>
        /// <returns></returns>
        private DataTable SearchServiceItemInfo(DataSet dsServiceItem, string sKeyword)
        {
            DataTable dtSearchCustom = dsServiceItem.Tables[0].Copy();
            DataTable dtReturn = dtSearchCustom.Clone();

            //服务项目编码
            DataRow[] drSerchRows = SearchFieldName(dtSearchCustom, DBEntityServiceItem.FieldName.SERVICEITEMCODE, sKeyword);
            CopyDataRow(drSerchRows, ref dtReturn);

            //服务项目名称
            drSerchRows = SearchFieldName(dtSearchCustom, DBEntityServiceItem.FieldName.SNAME, sKeyword);
            CopyDataRow(drSerchRows, ref dtReturn);

            //快速定位码
            drSerchRows = SearchFieldName(dtSearchCustom, DBEntityServiceItem.FieldName.SINDEXCODE, sKeyword);
            CopyDataRow(drSerchRows, ref dtReturn);

            //服务次数
            drSerchRows = SearchFieldName(dtSearchCustom, DBEntityServiceItem.FieldName.SCOUNT, sKeyword);
            CopyDataRow(drSerchRows, ref dtReturn);

            //有效服务天数
            drSerchRows = SearchFieldName(dtSearchCustom, DBEntityServiceItem.FieldName.SAVAILABLEDAYS, sKeyword);
            CopyDataRow(drSerchRows, ref dtReturn);

            //服务开始时间
            drSerchRows = SearchFieldName(dtSearchCustom, DBEntityServiceItem.FieldName.STARTDATE, sKeyword);
            CopyDataRow(drSerchRows, ref dtReturn);

            drSerchRows = SearchFieldName(dtSearchCustom, DBEntityServiceItem.FieldName.SENDDATE, sKeyword);
            CopyDataRow(drSerchRows, ref dtReturn);

            return dtReturn;
        }

        /// <summary>
        /// 指定字段搜索数据集
        /// </summary>
        /// <param name="dtData"></param>
        /// <param name="serchFieldName"></param>
        /// <param name="serchValue"></param>
        /// <returns></returns>
        private DataRow[] SearchFieldName(DataTable dtData, string serchFieldName, string serchValue)
        {
            DataTable dtReturn = dtData.Clone();
            foreach (DataRow dr in dtData.Rows)
            {
                if (dr[serchFieldName] == System.DBNull.Value)
                    continue;

                if (dr[serchFieldName].ToString().ToUpper().IndexOf(serchValue.ToUpper()) < 0)
                    continue;

                dtReturn.ImportRow(dr);
                dr.Delete();
            }
            dtReturn.AcceptChanges();
            dtData.AcceptChanges();
            return dtReturn.Select();
        }

        /// <summary>
        /// 对数据集行进行复制
        /// </summary>
        /// <param name="drCopyRow"></param>
        /// <param name="dtSearch"></param>
        private void CopyDataRow(DataRow[] drCopyRow, ref DataTable dtSearch)
        {
            foreach (DataRow dr in drCopyRow)
            {
                dtSearch.ImportRow(dr);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (Validation() == false)
            {
                return;
            }

            if (_mode == ControlClassModeEnum.emInsert)
            {
                _customerserviceitem = new DBEntityCustomerServiceItem();
                _customerserviceitem.CUSTOMERID = _customerid;
                _customerserviceitem.SERVICEITEMID = _serviceitemid;
            }
            _customerserviceitem.CBUYTIME = dtiBuyTime.Value;
            _customerserviceitem.CMEMO = txtMemo.Text;
            _customerserviceitem.COUNT = iiServiceCount.Value;
            _customerserviceitem.CREMAINCOUNT = iiRemainServiceCount.Value;
            _customerserviceitem.CSERVICEENDTIME = dtiEndTime.Value;
            _customerserviceitem.CSERVICESTARTTIME = dtiStartTime.Value;
            _customerserviceitem.CTOTALNEEDPAY = Convert.ToDecimal(txtMoney.Text.Trim());
            _customerserviceitem.CBUYMONEY = Convert.ToDecimal(textCBuyMoney.Text.Trim());
            string sState = cbeState.SelectedItem.ToString();
            if (sState == DBEntityCustomerServiceItem.ENUM_CSTATUS.C0A_CHINESE)
                _customerserviceitem.CSTATUS = DBEntityCustomerServiceItem.ENUM_CSTATUS.C0A;
            else if (sState == DBEntityCustomerServiceItem.ENUM_CSTATUS.C0E_CHINESE)
                _customerserviceitem.CSTATUS = DBEntityCustomerServiceItem.ENUM_CSTATUS.C0E;

            string error = string.Empty;
            bool bFlag = false;
            if (_mode == ControlClassModeEnum.emInsert)
            {
                bFlag = BussinessProxyManager.Instance.InsertCustomerServiceItem(_customerserviceitem, out error);
                if (bFlag == false)
                {
                    MsgBox.MsgInfo("新增会员服务项目信息失败\r\n" + error);
                    return;
                }
            }
            else
            {
                bFlag = BussinessProxyManager.Instance.UpdateCustomerServiceItem(_customerserviceitem, out error);
                if (bFlag == false)
                {
                    MsgBox.MsgInfo("修改会员服务项目信息失败\r\n" + error);
                    return;
                }
            }
            if (bFlag == true)
            {
                MsgBox.MsgInfo("保存成功。");
                this.DialogResult = DialogResult.OK;
            }
        }

        private bool Validation()
        {
            string error = string.Empty;
            if (_serviceitemid == -1)
            {
                MsgBox.MsgInfo("请先选择服务项目。");
                return false;
            }
            if (cbeState.SelectedIndex < 0)
            {
                error = "请选择状态。";
                MsgBox.MsgInfo(error);
                cbeState.Focus();
                SetErrorControl(cbeState, error);
                return false;
            }
            if (dtiBuyTime.Text == string.Empty)
            {
                error = "请选择购买时间。";
                MsgBox.MsgInfo(error);
                dtiBuyTime.Focus();
                SetErrorControl(dtiBuyTime, error);
                return false;
            }
            if (iiServiceCount.Text == string.Empty)
            {
                error = "请输入服务次数。";
                MsgBox.MsgInfo(error);
                iiServiceCount.Focus();
                SetErrorControl(iiServiceCount, error);
                return false;
            }
            if (iiRemainServiceCount.Text == string.Empty)
            {
                error = "请输入剩余服务次数。";
                MsgBox.MsgInfo(error);
                iiRemainServiceCount.Focus();
                SetErrorControl(iiRemainServiceCount, error);
                return false;
            }
            if (iiRemainServiceCount.Value > iiServiceCount.Value)
            {
                MsgBox.MsgInfo("剩余服务次数不允许大于服务次数。");
                return false;
            }
            if (dtiStartTime.Text == string.Empty)
            {
                error = "请输入服务项目开始时间。";
                MsgBox.MsgInfo(error);
                dtiStartTime.Focus();
                SetErrorControl(dtiStartTime, error);
                return false;
            }
            if (dtiEndTime.Text == string.Empty)
            {
                error = "请输入服务项目结束时间。";
                MsgBox.MsgInfo(error);
                dtiEndTime.Focus();
                SetErrorControl(dtiEndTime, error);
                return false;
            }
            if (dtiStartTime.Value > dtiEndTime.Value)
            {
                MsgBox.MsgInfo("服务项目开始时间不允许大于服务项目结束时间。");
                return false;
            }
            if (txtMoney.Text.Trim() == string.Empty)
            {
                error = "请输入欠款。";
                MsgBox.MsgInfo(error);
                txtMoney.Focus();
                SetErrorControl(txtMoney, error);
                return false;
            }
            bool bFlag = NumberUtil.IsNonNegativeDecimal(txtMoney.Text.Trim());
            if (bFlag == false)
            {
                error = "欠款应为数字，请输入正确的数字。";
                MsgBox.MsgInfo(error);
                txtMoney.Focus();
                SetErrorControl(txtMoney, error);
                return false;
            }

            bFlag = NumberUtil.IsNonNegativeDecimal(textCBuyMoney.Text.Trim());
            if(bFlag == false){
                error = "实际支付为数字，请输入正确的数字。";
                MsgBox.MsgInfo(error);
                textCBuyMoney.Focus();
                SetErrorControl(textCBuyMoney, error);
                return false;
            }
            return true;
        }

        private void frmCustomerServiceItemAdd_Shown(object sender, EventArgs e)
        {
            dtiEndTime.Enabled = false;
            if (_mode == ControlClassModeEnum.emEdit)
            {
                _serviceitemid = _customerserviceitem.SERVICEITEMID;
                _customerid = _customerserviceitem.CUSTOMERID;
                lblItemName.Text = _customerserviceitem.SNAME;
                lblCode.Text = _customerserviceitem.SERVICEITEMCODE;
                lblPrice.Text = _customerserviceitem.SPRICE.ToString();
                lblTimeSpan.Text = _customerserviceitem.STIMESPAN.ToString();

                if (_customerserviceitem.CSTATUS == DBEntityCustomerServiceItem.ENUM_CSTATUS.C0A)
                    cbeState.SelectedIndex = 0;
                else if (_customerserviceitem.CSTATUS == DBEntityCustomerServiceItem.ENUM_CSTATUS.C0E)
                    cbeState.SelectedIndex = 1;

                dtiBuyTime.Value = _customerserviceitem.CBUYTIME;
                iiServiceCount.Text = _customerserviceitem.COUNT.ToString();
                iiRemainServiceCount.Text = _customerserviceitem.CREMAINCOUNT.ToString();
                dtiStartTime.Value = _customerserviceitem.CSERVICESTARTTIME;
                dtiEndTime.Value = _customerserviceitem.CSERVICEENDTIME;
                txtMemo.Text = _customerserviceitem.CMEMO;
                txtMoney.Text = _customerserviceitem.CTOTALNEEDPAY.ToString();
                textCBuyMoney.Text = _customerserviceitem.CBUYMONEY.ToString();

                //if (_customerserviceitem.CALLBACKFLAG == 1)
                //{
                //    cbCallBackFlag.Checked = true;
                //    txtCallBackDays.Text = _customerserviceitem.CALLBACKDAYS.ToString();
                //}
                //else
                //{
                //    cbCallBackFlag.Checked = false;
                //}

                serviceItemSearch1.Enabled = false;
            }
            else
            {
                dtiBuyTime.Value = DateTime.Now;
                dtiStartTime.Value = DateTime.Now;
                dtiEndTime.Value = DateTime.Now;
                cbeState.SelectedIndex = 0;
            }
            cbCallBackFlag_CheckedChanged(null, null);
        }

        private void cbCallBackFlag_CheckedChanged(object sender, EventArgs e)
        {
        }
    }
}
